package Listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;

import View.ServerScreen;
import View.TableTab;
import XML.XMLHelper;

public class ButtonAddListener implements ActionListener{

	private static String formatString(String input){
		String output = "";
		int begin = 0, end = input.length()-1;
		for(int i = 0; i < input.length(); i++){
			if(input.charAt(i) != ' '){
				begin = i;
				break;
			}
		}
		
		for(int i = input.length() - 1; i >= 0; i--){
			if(input.charAt(i) != ' '){
				end = i;
				break;
			}
		}
		
		if(input.charAt(begin) == ' ')
			output = "";
		else
			output = input.substring(begin, end + 1);
		
		if(output != ""){
			output = output.toLowerCase();
		}

		return output;
	}
	
	public boolean nodeIsExist(String name){
		for(int i = 0; i < ServerScreen.top.getChildCount(); i++)
		{
			if(ServerScreen.top.getChildAt(i).toString().compareTo(name) == 0)
				return true;
		}
		return false;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String option = JOptionPane.showInputDialog(ServerScreen.frame, "Please enter table's name: ", 
				"Table Name", 1);
	
		if(option != null && option.compareTo("") != 0){
			option = formatString(option);
			
			nodeIsExist(option);
			//JOptionPane.showMessageDialog(ServerScreen.frame, "Create new table! Success!!!");
			if(XMLHelper.IsExist(ServerScreen.database.getName(), option) == false && !nodeIsExist(option)){
				DefaultMutableTreeNode newTable = new DefaultMutableTreeNode(option);
				ServerScreen.treeModel.insertNodeInto(newTable, ServerScreen.top, ServerScreen.top.getChildCount());
				
				TableTab newTab = new TableTab(option);
				ServerScreen.tableOpened.add(option);
			}else{
				JOptionPane.showMessageDialog(ServerScreen.frame, "Table exists", "Error", JOptionPane.OK_OPTION);
			}
			
		}else{
			JOptionPane.showMessageDialog(ServerScreen.frame, "Create new table! Cancel!!!");
		}
	}	
}
